package com.lglbc.oauth2.config;

import com.lglbc.oauth2.common.UserContextUtil;
import com.nimbusds.jose.JWSObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            return true;
        }
        String token = StringUtils.substringAfter(authorization, "Bearer ");
        if (StringUtils.isBlank(token)) {
            return true;
        }
        try {
            Map<String, Object> stringObjectMap = JWSObject.parse(token).getPayload().toJSONObject();
            UserContextUtil.setUser(stringObjectMap);
        } catch (Exception e) {

        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextUtil.removeUser();
    }
}
